﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using SiteServer.Plugin;
using Thingpower.SS.EduOnline.Model;

namespace Thingpower.SS.EduOnline.Provider
{
    public class CoursewareStudyUsersDAO : BaseDAO
    {
        public const string TableName = "view_CoursewareStudyUsers";

        public static List<CoursewareStudyUsersInfo> GetAllModelsList()
        {
            var list = new List<CoursewareStudyUsersInfo>();

            string sqlString =
                $"SELECT CoursewareId, UserId, UserName, Mobile, DisplayName, Times FROM {TableName} ORDER BY {nameof(CoursewareStudyUsersInfo.UserId)}";

            using (var rdr = DataApi.ExecuteReader(ConnectionString, sqlString))
            {
                while (rdr.Read())
                {
                    list.Add(GetModel(rdr));
                }
                rdr.Close();
            }

            return list;
        }

        public static List<CoursewareStudyUsersInfo> GetModelsList(int coursewareId)
        {
            var list = new List<CoursewareStudyUsersInfo>();

            string sqlString =
                $"SELECT CoursewareId, UserId, UserName, Mobile, DisplayName, Times FROM {TableName} WHERE CoursewareId = {coursewareId} ORDER BY {nameof(CoursewareStudyUsersInfo.Times)}";

            using (var rdr = DataApi.ExecuteReader(ConnectionString, sqlString))
            {
                while (rdr.Read())
                {
                    list.Add(GetModel(rdr));
                }
                rdr.Close();
            }

            return list;
        }

        private static CoursewareStudyUsersInfo GetModel(IDataRecord rdr)
        {
            if (rdr == null) return null;

            var _model = new CoursewareStudyUsersInfo();

            var i = 0;
            _model.CoursewareId = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);
            i++;
            _model.UserId = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);
            i++;
            _model.UserName = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            _model.Mobile = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            _model.Region = rdr.IsDBNull(i) ? string.Empty : rdr.GetString(i);
            i++;
            _model.Times = rdr.IsDBNull(i) ? 0 : rdr.GetInt32(i);

            return _model;
        }
    }
}